package com.example.demo.controller;

import com.example.demo.config.OssConfig;
import com.example.demo.entity.DTO.FileDTO;
import com.example.demo.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/*
 *
 *   @auto:软件 weiyang
 *   @Date 2024/6/1 9:10
 *      文件相关的上传
 */
@Api(tags = "文件相关的上传")
@RestController
@RequestMapping("/file")
public class FilesController {
    @Autowired
    private OssConfig ossConfig;

    //上传文件接口
    @ApiOperation(value = "通用上传文件的接口")
    @PostMapping("/upload")
    public Result<FileDTO> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("文件类型")String fileType) throws IOException {
        //数据库保存里面
        String path = ossConfig.putObject(file, fileType);
        //文件回显路径
        String url = "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + path;
        return Result.success(new FileDTO(url, path));
    }

    /**
     * 多文件上传
     * @param files
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "多文件上传")
    @PostMapping("/upload/elements")
    public Result<List<FileDTO>> uploadElementFileMulti(@RequestParam("file") MultipartFile[] files,@RequestParam("文件类型") String fileType) throws IOException {
        List<FileDTO> filesName = new ArrayList<>();
        for (MultipartFile file : files) {
            FileDTO fileDTO = new FileDTO();
            if(file.isEmpty()){
                return Result.error().msg("文件为空，不能上传");
            }
            String fileName = ossConfig.putObject(file, fileType);
            fileDTO.setUrl("https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint()+ "/" + fileName);
            fileDTO.setPath(fileName);
            filesName.add(fileDTO);
        }
        return Result.success(filesName).msg("上传成功");
    }
}
